import xml.etree.ElementTree as ET
import pandas as pd
from pathlib import Path

# XML文件路径
filename = 'C:/'

# 解析XML文件
treeG = None
rootG = None
arrP = []
allObject = []

xmlParamList = []
xmlDictList = []


# 解析Excel的表头
def AnalysisParam(file):
    tempTree = ET.parse(file)
    tempRoot = tempTree.getroot()
    for testcase in tempRoot.findall('.//capltestcase'):
        for param in testcase.findall('caplparam'):
            param_name = param.get('name')
            if param_name not in xmlParamList:
                xmlParamList.append(param_name)
    return xmlParamList, (tempTree, tempRoot)


def AnalysisText(paramList, root):
    for testcase in root.findall('.//capltestcase'):
        tempDict = {"TestcaseFunc": testcase.get('name'), "TestcaseTitle": testcase.get('title')}
        for param in testcase.findall('caplparam'):
            param_name = param.get('name')
            for name in paramList:
                if param_name == name:
                    if name not in tempDict:
                        tempDict[name] = param.text
        xmlDictList.append(tempDict)


def coverToExcel(data, targetPathFile):
    df = pd.DataFrame(data)
    df.to_excel(targetPathFile)
    # df.to_excel('C:\Personal\Python\library\output.xlsx')


if __name__ == '__main__':
    a, b = AnalysisParam(filename)
    AnalysisText(a, b[1])
    coverToExcel(xmlDictList, 'C:\Personal\Python\library\output.xlsx')
